package com.sskj.level.ui.fragment;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.header.MaterialHeader;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.CoinType;
import com.sskj.level.http.HttpConfig;
import com.sskj.level.presenter.SlideHangqingFragmentPresenter;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.mvchelper.RefreshDataSource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.LEVEL_FRAGMENT_SLIDE)//侧滑
public class SlideHangqingFragment extends BaseFragment<SlideHangqingFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private String code = "USDT";
    private MVCCoolHelper<List<StockCoinBean>> mvcHelper;
    private SlimAdapter<StockCoinBean> slimAdapter;
    private HashMap<String, Integer> coinImg;
    private Map<String, Disposable> timeMap = new HashMap<>();

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_slide_hangqing;
    }

    @Override
    public SlideHangqingFragmentPresenter getPresenter() {
        return new SlideHangqingFragmentPresenter();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebSocketMessage(StockCoinBean.StockProductVOBean stockSocketBean) {
        Flowable.fromIterable(slimAdapter.getData())
                .filter(item -> item.getStockProductVO().getCode().equals(stockSocketBean.getCode()))
                .subscribe(item -> {
                    if (Double.valueOf(stockSocketBean.getChange()) > 0) {
                        stockSocketBean.setGreen(true);
                    } else {
                        stockSocketBean.setGreen(false);
                    }
                    stockSocketBean.setLight(true);
                    item.setStockProductVO(stockSocketBean);
                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item), 1);
                    DisposUtil.close(timeMap.get(item.getStockProductVO().getCode()));
                    Disposable subscribe = Flowable.timer(600, TimeUnit.MILLISECONDS)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(i -> {
                                item.getStockProductVO().setLight(false);
                                slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item), 1);
                            });
                    timeMap.put(item.getStockProductVO().getCode(), subscribe);
                });
    }

    @Override
    public void initView() {
        coinImg = new HashMap<>();
        coinImg.put("BTC", R.mipmap.level_icon_btc);
        coinImg.put("BCH", R.mipmap.level_icon_bch);
        coinImg.put("ETC", R.mipmap.level_icon_etc);
        coinImg.put("ETH", R.mipmap.level_icon_ethicon);
        coinImg.put("LTC", R.mipmap.level_icon_ltc);
        coinImg.put("EOS", R.mipmap.level_icon_eos);
        coinImg.put("DASH", R.mipmap.level_icon_dash);
        coinImg.put("ZEC", R.mipmap.level_icon_zec);
        coinImg.put("XRP", R.mipmap.level_icon_xrp);

        coinImg.put(null, R.mipmap.level_icon_btc);
        RxBus.getDefault().register(this);
        coolRefreshView.setPullHeader(new MaterialHeader(getActivity()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setDividerColor(getResources().getColor(R.color.level_070))
        );

        initAdapter();
    }


    private void initAdapter() {
        slimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_hanging, new SlimInjector<StockCoinBean>() {
            @Override
            public void onInject(StockCoinBean stock, IViewInjector injector, List<Object> payloads) {
                if (payloads == null || payloads.size() == 0) {
                    injector.text(R.id.tv_sale_price, stock.getStockProductVO().getPrice())
                            .text(R.id.tv_cny_money, "≈" + stock.getStockProductVO().getCnyPrice() + " CNY")
                            .text(R.id.tv_type, stock.getCode().split("/")[0])
                            .text(R.id.tv_unit, "/" + stock.getCode().split("/")[1]);
                    if (TextUtils.isEmpty(stock.getCoinImg())) {
                        injector.image(R.id.iv_coin, coinImg.get(stock.getCode().split("/")[0]));
                    } else {
                        injector.image(R.id.iv_coin, HttpConfig.BASE_IMG_URL + stock.getCoinImg());
                    }
                } else {
                    injector.text(R.id.tv_sale_price, stock.getStockProductVO().getPrice())
                            .text(R.id.tv_cny_money, "≈" + stock.getStockProductVO().getCnyPrice() + " CNY")
                            .text(R.id.tv_type, stock.getCode().split("/")[0])
                            .text(R.id.tv_unit, "/" + stock.getCode().split("/")[1]);
                }
                double change = 0;
                try {
                    change = Double.valueOf(stock.getStockProductVO().getChange());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                if (change > 0) {
                    injector.background(R.id.tv_condition, R.drawable.level_shape_green);
                } else if (change == 0) {
                    injector.backgroundColor(R.id.tv_condition, getResources().getColor(R.color.commonTextCCC));
                } else {
                    injector.background(R.id.tv_condition, R.drawable.level_shape_red);
                }
                injector.text(R.id.tv_condition, stock.getStockProductVO().getChangeRate());
                if (stock.getStockProductVO().isLight()) {
                    if (stock.getStockProductVO().isGreen()) {
                        injector.textColor(R.id.tv_sale_price, getResources().getColor(R.color.level_market_down));
                    } else {
                        injector.textColor(R.id.tv_sale_price, getResources().getColor(R.color.level_market_up));
                    }
                } else {
                    injector.textColor(R.id.tv_sale_price, getResources().getColor(R.color.level_12243B));
                }
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    RxBus.getDefault().post(new CoinType(slimAdapter.getData().get(position).getCode()));
                    getActivity().finish();
                });
        RefreshDataSource<StockCoinBean> refreshDataSource = new RefreshDataSource<StockCoinBean>() {
            @Override
            public Flowable<List<StockCoinBean>> loadData() {
                return mPresenter.getProduct(code);
            }
        };
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(refreshDataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
    }

    @Override
    public void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
